<?php
namespace app\admin\controller\system;
use app\admin\model\SystemConfig;
use app\admin\model\SystemConfigGroup;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use smartybuilder\libs\Quickbuilder;
use think\App;
use think\facade\Db;

/**
 * Class Setconfig
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="配置设置")
 */
class Setconfig extends AdminController
{
    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemConfig();
    }
    protected $sort = [
        'sort'=>'desc'
    ];
    /**
     * @NodeAnotation(title="列表")
     */
    public function index(){
        if($this->request->isAjax()){
            $limit = $this->request->param('limit',15);
            $array = $this->model->order('group asc')->paginate($limit)->toArray();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $array['total'],
                'data'  => $array['data'],
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="生成配置页面")
     */
    public function createjs(){
        echo 'haha';
    }
    public function add()
    {
        if($this->request->isAjax()){
            $data = $this->request->param();
            $newdata = [
                'remark'=>$data['remark'],
                'group'=>!empty($data['groups'])?$data['groups']:$data['group'],
                'remark'=>$data['remark'],
                'name'=>$data['name'],
                'formtype'=>$data['formtype'],
                'option'=>$data['option'],
                'update_time'=>time(),
                'create_time'=>time(),
            ];
            $bool = $this->model->save($newdata);
            if($bool){
                return $this->success('添加成功');
            }else{
                return $this->error('添加失败');
            }
        }
        $group = SystemConfigGroup::where('status',1)->select()->toArray();
//        echo '<pre>';
//        print_r($group);
//        exit;
//        $group = array_column($group,'group');
        $formType = json_decode('{"input":"单行文本","textarea":"多行文本","file":"单文件","files":"多文件","img":"单图片","imgs":"多图片","video":"视频","radio":"单选框","checkbox":"多选框","select":"下拉框","color":"颜色","editor":"编辑框","none":"隐藏框","password":"密码框","optgroup":"下拉组","switch":"开关","json":"json数组","lradio":"联动单选框","lcheckbox":"联动多选框","lselect":"联动下拉框","datetime":"时间"}',true);
//        echo '<pre>';
//        print_r($formType);
//        exit;
        return $this->fetch('',['group'=>$group,'formType'=>$formType]);
    }
    public function edit($id)
    {
        if($this->request->isAjax()){
            $data = $this->request->param();
            $newdata = [
                'remark'=>$data['remark'],
                'group'=>!empty($data['groups'])?$data['groups']:$data['group'],
                'remark'=>$data['remark'],
                'name'=>$data['name'],
                'formtype'=>$data['formtype'],
                'option'=>$data['option'],
                'sort'=>$data['sort'],
                'update_time'=>time(),
            ];
            $bool = $this->model->where('id',$id)->save($newdata);
            if($bool){
                return  $this->success('修改成功');
            }else{
                return $this->error('修改失败');
            }
        }
        $data = $this->model->where('id',$id)->findOrEmpty()->toArray();
//        echo '<pre>';
//        print_r($data);
//        exit;
        $group = SystemConfigGroup::where('status',1)->select()->toArray();
//        $group = array_column($group,'group');
        $formType = json_decode('{"input":"单行文本","textarea":"多行文本","file":"单文件","files":"多文件","img":"单图片","imgs":"多图片","video":"视频","radio":"单选框","checkbox":"多选框","select":"下拉框","color":"颜色","editor":"编辑框","none":"隐藏框","password":"密码框","optgroup":"下拉组","switch":"开关","json":"json数组","lradio":"联动单选框","lcheckbox":"联动多选框","lselect":"联动下拉框","datetime":"时间"}',true);

        return $this->fetch('',['row'=>$data,'group'=>$group,'formType'=>$formType]);
    }
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }
    /**
     * @NodeAnotation(title="其他设置")
     */
    public function set_config(){
        $group = $this->request->param('group');
//        echo '<pre>';
//        print_r($group);
//        exit;
        $data = Db::name('system_config')
            ->where('group',$group)
            ->order('sort desc,group desc,remark desc')
            ->select()->toArray();
//        echo '<pre>';
//        print_r($data);
//        exit;
        $obj = new Quickbuilder();
        $obj = $obj->makeForm()
            ->setAction('/admin/system.setconfig/add_config?group='.$group);
//        echo '<pre>';
//        print_r($data);
//        exit;
        foreach ($data as $value){
            $obj->set_up_form($value['formtype'],$value['remark'],$value['name'],htmlspecialchars_decode($value['value']));
        }
        $obj->set_button('submit','提交')
            ->fetch();
//        return $obj;

    }
    /**
     * @NodeAnotation(title="添加新设置")
     */
    public function add_config(){
        $data = $this->request->param();
        $group = $this->request->param('group');
//        echo '<pre>';
//        print_r($data);
//        exit;
//        echo '<pre>';
//        print_r($data);
//        exit;
        unset($data['group']);
        $duoyou  = Db::name('system_config')
//            ->whereNotIn('group',['site','sms','upload','wechat'])
            ->where('group',$group)
            ->select()->toArray();
//        echo '<pre>';
//        print_r($duoyou);
//        exit;
        foreach ($duoyou as $key=>$value){

            if($value['formtype']=='switch'){
                if(isset($data[$value['name']])){
                    $bool = Db::name('system_config')
                        ->where('id',$value['id'])
                        ->update(['value'=>1]);
                }else{
                    $bool = Db::name('system_config')
                        ->where('id',$value['id'])
                        ->update(['value'=>0]);
                }
            }elseif ($value['formtype']=='editor'){
                if(isset($data[$value['name']])){
                    $bool = Db::name('system_config')
                        ->where('id',$value['id'])
                        ->update(['value'=>htmlspecialchars_decode($data[$value['name']])]);
                }
            }else{
                if(isset($data[$value['name']])){
                    $bool = Db::name('system_config')
                        ->where('id',$value['id'])
                        ->update(['value'=>$data[$value['name']]]);
                }
            }
        }
        return $this->redirect('/admin/system.Setconfig/set_config?group='.$group);
    }

}